from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


# Create your models here.
class CaptchaModel(models.Model):
    email = models.EmailField(unique=True)
    captcha = models.CharField(max_length=4)
    create_time = models.DateTimeField(auto_now_add=True)


class UserProfile(models.Model):
    """用户扩展信息（昵称、性别、简介等）"""
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        related_name='profile',
        verbose_name='关联用户'
    )
    nickname = models.CharField(
        max_length=50,
        blank=True,
        default='',
        verbose_name='用户昵称'
    )
    GENDER_CHOICES = [
        ('', '未选择'),
        ('male', '男'),
        ('female', '女'),
    ]
    gender = models.CharField(
        max_length=10,
        choices=GENDER_CHOICES,
        default='',
        verbose_name='性别'
    )
    avatar = models.ImageField(
        upload_to='avatars/',  # 上传路径（MEDIA_ROOT/avatars/）
        default='avatars/default.png',  # 默认头像
        blank=True,
        verbose_name='用户头像'
    )
    bio = models.TextField(blank=True, default='', verbose_name='个人简介')
    region = models.CharField(max_length=100, blank=True, default='', verbose_name='所在地区')
    birthday = models.DateField(null=True, blank=True, verbose_name='出生日期')

    class Meta:
        verbose_name = '用户信息'
        verbose_name_plural = '用户信息'


# 信号：用户创建时自动生成Profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()
